package com.ewzj.bigdata.mvp.presenter

import android.app.Application
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import cn.jzvd.JZVideoPlayerStandard
import com.bumptech.glide.Glide
import com.ewzj.bigdata.R
import com.ewzj.bigdata.app.config.AppKey
import com.ewzj.bigdata.app.extensions.loadImgwithloading
import com.ewzj.bigdata.app.utils.Apputils
import com.ewzj.bigdata.app.utils.RxUtils
import com.ewzj.bigdata.mvp.contract.CitySelectorActivityContract
import com.ewzj.bigdata.mvp.contract.VideoWebviewActivityContract
import com.ewzj.bigdata.mvp.model.bean.CitygroupBean
import com.ewzj.bigdata.mvp.model.bean.JsCommentbean
import com.ewzj.bigdata.mvp.model.bean.JsReplayBean
import com.ewzj.bigdata.mvp.model.bean.JsReqcommentBean
import com.ewzj.bigdata.mvp.model.reqbean.*
import com.ewzj.bigdata.mvp.model.rspbean.*
import com.ewzj.bigdata.mvp.ui.activity.LoginActivity
import com.ewzj.bigdata.mvp.ui.adapter.CityAdapter
import com.ewzj.bigdata.mvp.ui.adapter.HotcityAdapter
import com.github.lzyzsd.jsbridge.BridgeHandler
import com.github.lzyzsd.jsbridge.BridgeWebView
import com.github.lzyzsd.jsbridge.CallBackFunction
import com.google.gson.Gson
import com.jess.arms.mvp.BasePresenter
import com.jess.arms.utils.DataHelper
import com.jess.arms.utils.DeviceUtils
import com.jess.arms.utils.UiUtils
import com.umeng.socialize.ShareAction
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observables.GroupedObservable
import io.reactivex.schedulers.Schedulers
import me.jessyan.rxerrorhandler.core.RxErrorHandler
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber
import okhttp3.RequestBody
import java.util.*
import javax.inject.Inject

/**
 * author:zhangjing
 * 作用:
 * return:
 */
class VideoWebActivityPresenter @Inject constructor(val mGson: Gson, val mErrorHandler: RxErrorHandler, val application: Application, view: VideoWebviewActivityContract.View, model: VideoWebviewActivityContract.Model) : BasePresenter<VideoWebviewActivityContract.Model, VideoWebviewActivityContract.View>(model, view) {
    private var talkFunction: CallBackFunction? = null
    private var zanFunction: CallBackFunction? = null
    private var linkFunction: CallBackFunction? = null
    val context = mRootView as AppCompatActivity
    private var replayBean: JsReplayBean? = null
    var commentType = 1
    lateinit var webview: BridgeWebView
    fun initVideo(videoplayer: JZVideoPlayerStandard, video: VideoBean) {
        JZVideoPlayerStandard.SAVE_PROGRESS=false
        videoplayer.thumbImageView.scaleType = ImageView.ScaleType.FIT_XY
        videoplayer.startButton.setImageResource(R.drawable.btn_play)
        videoplayer.setUp(video.getVideo(), JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, "")
        videoplayer.backButton.visibility = View.GONE
        videoplayer.thumbImageView.loadImgwithloading(video.thumb)
    }

    fun initJsBridge(bridgeWebView: BridgeWebView) {
        webview = bridgeWebView;
        bridgeWebView.registerHandler("talkTalk", BridgeHandler { data, function ->
            talkTalk(data)
            talkFunction = function
        })
        bridgeWebView.registerHandler("zanTalk", BridgeHandler { data, function ->
            zanTalk(data)
            zanFunction = function
        })

        bridgeWebView.registerHandler("linkOther", BridgeHandler { data, function ->
            linkOther(data)
            linkFunction = function
        })
    }

    private fun  linkOther(data: String?) {
        Observable.just(data).map { t ->mGson.fromJson(data,VideoBean::class.java) }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxUtils.bindToLifecycle(mRootView))
                .subscribe(object :ErrorHandleSubscriber<VideoBean>(mErrorHandler){
                    override fun onNext(t: VideoBean) {
                        mRootView.refreshVideo(t!!)
                    }

                })
    }

    fun zanTalk(json: String) {
        if (!Apputils.Utils.checkIsLogin(context)) {
            LoginActivity.startLoginActivity(context)
            return
        }

        Observable.just(json).map({
            t ->
            mGson.fromJson(t, JsCommentbean::class.java)
        }).map({ t ->
            val reqpraise = ReqPraise()
            run {
                reqpraise.table_id = t.getGroupId()
                reqpraise.list_id = t.getId()
                reqpraise.praise =1
            }
            reqpraise
        }).flatMap({ t: ReqPraise -> mModel.doPraise(t) }).compose(RxUtils.applySchedulers(mRootView))
                .subscribe({ t ->
                    zanFunction!!.onCallBack(json)
                }, { UiUtils.SnackbarText("") })
    }


    fun talkTalk(name: String) {
        if (!Apputils.Utils.checkIsLogin(context)) {
            LoginActivity.startLoginActivity(context)
            return
        }
        commentType = 2
        Observable.just(name).map { t -> mGson.fromJson(name, JsReplayBean::class.java)
        }
                .subscribeOn(AndroidSchedulers.mainThread())
                .map { t ->
                    t.apply {
                        mRootView.setHintText(t!!.tishi)
                    }
                }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :ErrorHandleSubscriber<JsReplayBean>(mErrorHandler){
                    override fun onNext(t: JsReplayBean) {
                        replayBean=t
                        mRootView.showComentBar()
                    }

                })
//                .subscribe(object : ErrorHandleSubscriber<JsReplayBean>(mErrorHandler) {
//                    override fun onNext(t: JsReplayBean?) {
//                        mRootView.showComentBar()
//                    }
//
//                })
    }
    fun doCollect(video: VideoBean) {
        Observable.just(video).map { t ->
            val reqNormalCollect = ReqNormalCollect()
            kotlin.run {
                reqNormalCollect.list_id = video.id
                reqNormalCollect.table_id = video.getGroupId()
            }
            reqNormalCollect
        }.flatMap { t -> mModel.doCollect(t) }
                .compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object : ErrorHandleSubscriber<BaseData<Any>>(mErrorHandler) {
                    override fun onNext(t: BaseData<Any>) {
                        if (AppKey.mchaneObject is VideoBean){
                            if ((AppKey.mchaneObject as VideoBean).is_collect==1){
                                (AppKey.mchaneObject as VideoBean).is_collect=0
                            }else{
                                (AppKey.mchaneObject as VideoBean).is_collect=1
                            }
                        }else if (AppKey.mchaneObject is CollectionBean){
                            if ((AppKey.mchaneObject as CollectionBean).is_collect==1){
                                (AppKey.mchaneObject as CollectionBean).is_collect=0
                            }else{
                                (AppKey.mchaneObject as CollectionBean).is_collect=1
                            }
                        }

                        mRootView.setCollectState()
                    }
                }
                )
    }

    fun doComment(content: String, video: VideoBean) {
        DeviceUtils.hideSoftKeyboard(context, webview)
        if (content.isNullOrEmpty()) {
            UiUtils.SnackbarText("评论内容不能为空")
            return
        }
        Observable.just(content).map { t ->
            var reqcomment = Reqcomentbean()
            reqcomment.content=content
            run {
                if (commentType==1){
                    reqcomment.table_id=video.groupId.toInt()
                    reqcomment.list_id=video.id.toInt()
                }else if(commentType==2){
                    reqcomment.list_id = replayBean!!.getId()
                    reqcomment.table_id = replayBean!!.getGroupId()
                    reqcomment.id = replayBean!!.getTalkId()
                }
            }
            reqcomment
        }.flatMap { t ->mModel.doComment(t)  }
                .compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object :ErrorHandleSubscriber<BaseData<CommentBean>>(mErrorHandler){
                    override fun onNext(t: BaseData<CommentBean>) {
                        if (commentType==1){
                            mRootView.showMessage("评论成功")
                            webview.callHandler("afterTalk", mGson.toJson(t.data)) { }
                        }else{
                            val jsReplayBean = JsReqcommentBean()
                            jsReplayBean.nickname = t.data!!.getNickname()
                            jsReplayBean.setReply(t.data!!.getContent())
                            jsReplayBean.setTalkId(replayBean!!.getTalkId().toString() + "")
                            jsReplayBean.setGroupId(replayBean!!.getGroupId().toString() + "")
                            jsReplayBean.setListId(replayBean!!.getId().toString() + "")
                            jsReplayBean.setTishi(replayBean!!.getTishi())
                            talkFunction!!.onCallBack(mGson.toJson(jsReplayBean))
                            mRootView.showMessage("回复成功")
                        }
                        commentType = 1
                        mRootView.setHintText("请输入你的评论")
                    }

                })
    }

    fun ShareWeb(infodata: VideoBean, share: SHARE_MEDIA) {
        val web = UMWeb(infodata.go_url)
        if (!infodata.thumb.isNullOrEmpty()){
            val thumb = UMImage(context, infodata.thumb)
            web.setThumb(thumb)
        }else{
            val thumb = UMImage(context, R.drawable.share_default)
            web.setThumb(thumb)
        }
        if (TextUtils.isEmpty(infodata.summary)){
            web.description = "觅窝.新媒体"
        }else{
            web.description=infodata.summary
        }
//        web.description = infodata.
        web.title = infodata.title
        ShareAction(context).withMedia(web).setPlatform(share).setCallback(AppKey.umShareListener).share()
    }
}